package com.pmcc.core.web;

import com.pmcc.core.config.security.JwtUser;
import com.pmcc.core.entity.security.Organization;
import com.pmcc.core.repository.OrganizationRepository;
import com.pmcc.core.service.OrganizationService;
import com.pmcc.utils.BeanUtils;
import com.pmcc.utils.ResultBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController()
@RequestMapping("api/v1/organizations")
@Api(value = "OrganizationController", description = "用户相关api")
public class OrganizationController {

    @Autowired
    OrganizationService organizationService;

    @Autowired
    private OrganizationRepository organizationRepository;

    @ApiOperation(value = "获取列表", notes = "")
    @GetMapping()
    public ResultBean query() {
        ResultBean resultBean = new ResultBean();
        resultBean.setResultCode(ResultBean.SUCCESS);
        resultBean.setRows(organizationService.queryList());
        return resultBean;
    }

    /**
     * 查询机构tree
     * 角色权限分配用
     * 非机构管理使用（不能查询出禁用组织机构）
     *
     * @return
     */
    @GetMapping("queryTree")
    public ResultBean queryTree(String id) {
        ResultBean resultBean = new ResultBean();
        resultBean.setResultCode(ResultBean.SUCCESS);
        resultBean.setRows(organizationService.queryTree(id));
        return resultBean;
    }


    @PostMapping("")
    public ResultBean create(@RequestBody Organization organization) {
        JwtUser jwtUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        ResultBean resultBean = new ResultBean();
        resultBean.setResultCode(ResultBean.SUCCESS);
        if (organization.getParentId() == null) {//如果没有选择上级单位
            organization.setParentId("0");
            organization.setLevel(0);
        } else {
            Organization parent = organizationRepository.findOne(organization.getParentId());
            organization.setLevel(parent.getLevel() + 1);
        }
        organization.setDelFlag("0");
        organization.setCreateId(jwtUser.getId());
        organization.setCreateName(jwtUser.getUsername());
        organization.setCreateTime(new Date());
        organizationRepository.save(organization);
        return resultBean;
    }

    @PutMapping("")
    public ResultBean edit(@RequestBody Organization organization) {
        ResultBean resultBean = new ResultBean();
        try {
            JwtUser jwtUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            Organization obj = organizationRepository.findOne(organization.getId());
            BeanUtils.copyProperties(organization, obj);
            obj.setModifyId(jwtUser.getUsername());
            obj.setModifyName(jwtUser.getId());
            obj.setModifyTime(new Date());
            organizationRepository.save(obj);
            resultBean.setResultCode(ResultBean.SUCCESS);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    /**
     * 删除
     *
     * @param
     * @return
     */
    @DeleteMapping()
    @ResponseBody
    public ResultBean delete(@RequestBody Map<String, String> map) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        if (map.containsKey("ids")) {
            if (map.get("ids") != null) {
                String[] idArr = map.get("ids").split(",");
                for (String id : idArr) {
                    List list = organizationRepository.findByParentIdAndDelFlagOrderBySortNoAsc(id, "0");
                    if (list != null && list.size() > 0) {
                        resultBean.setResultCode(ResultBean.FAIL);
                        resultBean.setResultDesc("该组织机构存在未删除的子节点！");
                        return resultBean;
                    }
                    Organization obj = organizationRepository.findOne(id);
                    obj.setDelFlag("1");
                    organizationRepository.save(obj);
                }
            }
        }
        return resultBean;
    }
}

